// Fill out your copyright notice in the Description page of Project Settings.


#include "CharacterZD/Core/MonsterAIController.h"

#include "EngineUtils.h"
#include "CharacterZD/Core/TowerZD.h"
#include "TF_20240717/StoneDefenceUtils.h"


// Sets default values
AMonsterAIController::AMonsterAIController()
{
	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
}

// Called when the game starts or when spawned
void AMonsterAIController::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void AMonsterAIController::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

AActor* AMonsterAIController::FindTarget()
{
	auto GetRecentlyTower = [this](const TArray<ATowerZD*>& MyTowers) -> ATowerZD*
	{
		if (MyTowers.Num() > 0)
		{
			float TowerTargetDistance = 99999999.0f;
			int32 TowerIndex = INDEX_NONE;
			FVector MyLocation = GetPawn()->GetActorLocation();
			for (int32 i = 0; i < MyTowers.Num(); i++)
			{
				if (ATowerZD* TowerCharacter = MyTowers[i])
				{
					FVector TowerLocation = TowerCharacter->GetActorLocation();
					FVector TmpLocation = TowerLocation - MyLocation;
					float TowerAndMonsterDistance = TmpLocation.Size();
					if (TowerAndMonsterDistance < TowerTargetDistance)
					{
						TowerIndex = i;
						TowerTargetDistance = TowerAndMonsterDistance;
					}
				}
			}
			if (TowerIndex !=  INDEX_NONE)
			{
				return MyTowers[TowerIndex];
			}
		}
		return nullptr;
	};
	
	TArray<ARuleCharacterZD*> TargetMainTowersArray;
	TArray<ARuleCharacterZD*> TargetTowersArray;
	for (TActorIterator<ATowerZD>it(GetWorld(), ATowerZD::StaticClass()); it; ++it)
	{
		ATowerZD* TheCharacter = *it;
		if (TheCharacter && TheCharacter->IsActive())
		{
			if (TheCharacter->GetType() == EGameCharacterType::TOWER)
			{
				TargetTowersArray.Add(TheCharacter);
			}
			else if (TheCharacter->GetType() == EGameCharacterType::MAIN_TOWER)
			{
				TargetMainTowersArray.Add(TheCharacter);
			}
		}
	}

	ATowerZD* MainTowers = Cast<ATowerZD>(StoneDefenceUtils::FindTargetRecently(TargetMainTowersArray, GetPawn()->GetActorLocation()));
	ATowerZD* NorTowers = Cast<ATowerZD>(StoneDefenceUtils::FindTargetRecently(TargetTowersArray, GetPawn()->GetActorLocation()));
	
	return MainTowers && MainTowers->IsActive() ? MainTowers : NorTowers; 
}

void AMonsterAIController::AttackTarget(ARuleCharacterZD* Target)
{
	Super::AttackTarget(Target);

	GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, TEXT(" Monster Attack!"));
}

